import React, { useRef, useState } from 'react';
import { connect } from 'umi';
import { message } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { SchemaManage } from '@/components/SchemaComponent';
import { AuthClientManageAPI } from '../common/type';
import { getManageSearchColumns, getManageTableColumns } from '../mconfig';
import { UpdateModal } from './UpdateModal';
import { AuthClientManageService, isOpenService } from '../service';
import { TipsErrorModalNew } from '@/components/TipsErrorModalNew';
import _ from 'lodash';

/**
 * 定义认证客户端管理页面
 * @param curRes
 * @returns
 */
const AuthClientManageView: React.FC<AuthClientManageAPI.IManageType> = ({
  curRes,
}) => {
  const schemaManageRef: any = useRef();

  const tipErrorModalRef: any = useRef();

  /** 获取管理页面业务逻辑上下文内容 */
  const { loading, pagination, data, refreshRequest, reloadRefreshRequest } =
    AuthClientManageService(curRes);

  /** 控制认证弹框 */
  const [clientUpdateObj, setClientUpdateObj] = useState<Record<string, any>>({
    openUpdate: false,
    checkRows: {},
  });

  /** 控制修改弹框 */
  const [changeStateModal, setChangeStateModal] = useState<Record<string, any>>(
    {
      openChangeState: false,
      checkRows: {},
    },
  );

  /** 保存选中数据 */
  const [selectRowKeys, setSelectRowKeys] = useState<string[]>([]);

  /** 点击搜索按钮 */
  const onSearch = (requestParams: AuthClientManageAPI.ITableRequestType) => {
    refreshRequest(requestParams);
  };

  /** 点击搜索重置按钮 */
  const onReset = (requestParams: any) => {
    refreshRequest(requestParams);
  };

  /** 点击分页操作 */
  const onPageChange = (current: any, pageSize: any, params: any) => {
    refreshRequest({ pageSize, current, ...params });
  };

  /** 管理页面头部操作集合 */
  const getSearchOperateFuncs: AuthClientManageAPI.IHeaderActionType =
    React.useMemo(() => {
      return [
        {
          title: '添加',
          visible: curRes?.['/clientController/add'] ?? false,
          type: 'primary',
          icon: <PlusOutlined />,
          onClick: () => {
            setClientUpdateObj({
              openUpdate: true,
              checkRows: {},
            });
          },
        },
      ];
    }, [curRes, selectRowKeys]);

  /** 数据表格操作集合 */
  const getTableOperateFuncs: AuthClientManageAPI.ITableActionType = {
    onEdit: (record) => {
      setClientUpdateObj({
        openUpdate: true,
        checkRows: record,
      });
    },

    onChange: (checked, record) => {
      if (checked) {
      } else {
        setChangeStateModal({
          openChangeState: true,
          checkRows: record,
        });
      }
    },
  };

  /** 获取数据表格数据列 */
  const getTableColumns: Record<string, any>[] = React.useMemo(() => {
    return getManageTableColumns(curRes, getTableOperateFuncs);
  }, [curRes]);

  /** 修改状态回调 */
  const isOpenCallllback = (res: any) => {
    if (res && res?.msgFlag) {
      message.success(res?.msg);
      reloadManage();
      tipErrorModalRef?.current?.onCloseModal();
    } else {
      message.error(res?.msg);
    }
  };

  /** 引入修改状态接口 */
  const { isOpenLoading, isOpenRun } = isOpenService(isOpenCallllback);

  /** 刷新管理页回调 */
  const reloadManage = () => {
    reloadRefreshRequest();
  };

  return (
    <>
      <SchemaManage
        ref={schemaManageRef}
        searchProps={{
          switchList: [],
          searchList: getManageSearchColumns(),
          onSwitch: () => {},
          onReset,
          onSearch,
        }}
        actionList={getSearchOperateFuncs}
        tableProps={{
          columns: getTableColumns,
          dataSource: data?.rows,
          loading: loading,
          pagination: pagination as any,
          rowKey: 'name',
          onPageChange: onPageChange,
        }}
      />

      {/* 新增编辑弹框 */}
      {clientUpdateObj?.openUpdate && (
        <UpdateModal
          checkRows={clientUpdateObj?.checkRows}
          onClose={() => {
            setClientUpdateObj({
              openUpdate: false,
              checkRows: {},
            });
          }}
          reloadManage={reloadManage}
        />
      )}

      {/* 单个取消提示 */}
      {changeStateModal?.openChangeState && (
        <TipsErrorModalNew
          ref={tipErrorModalRef}
          modalTip="禁用后，该认证将不可用！是否确认禁用？"
          onClose={() => {
            setChangeStateModal({
              openUpdate: false,
              checkRows: {},
            });
          }}
          modalOnOK={() => {
            const changePayload: Record<string, any> = {
              id: changeStateModal?.checkRows?.id,
              versionNum: changeStateModal?.checkRows?.versionNum,
              isOpen: 0,
            };
            isOpenRun(changePayload);
          }}
          modalLoading={isOpenLoading}
        />
      )}
    </>
  );
};

export default connect(({ baseLogin, navTab }: Record<string, any>) => ({
  curRes: baseLogin?.permissions,
  navTab,
}))(AuthClientManageView);
